package nl.zuiderfestival.raydance.model.storage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

import nl.zuiderfestival.raydance.model.LocalStorage;

public class RaySerializer {

	private String filename;

	public RaySerializer(String filename) {
		this.filename = filename;
		File f = new File(filename);
		if (!f.exists()) {
			createNewFile(filename);
		}
	}

	private void createNewFile(String fileName) {
		File file = new File(fileName);
		try {
			file.createNewFile();
			write(new LocalStorage());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void write(LocalStorage data) {
		//serialize the List
		ObjectOutput output;
		try {
			OutputStream file = new FileOutputStream(filename);
			OutputStream buffer = new BufferedOutputStream(file);
			output = new ObjectOutputStream(buffer);

			output.writeObject(data);
			output.close();
		}  catch(IOException ex){
			ex.printStackTrace();
		}
	}

	public LocalStorage read() {
		LocalStorage result = new LocalStorage();
		try {
			InputStream file = new FileInputStream(filename);
			InputStream buffer = new BufferedInputStream(file);
			ObjectInput input = new ObjectInputStream(buffer);

			//deserialize the List
			result = (LocalStorage)input.readObject();
			
			input.close();
		} catch (ClassNotFoundException ex){
			ex.printStackTrace();
		} catch(IOException ex){
			ex.printStackTrace();
		} catch (ClassCastException ex) {
			ex.printStackTrace();
		}
		return result;
	}
}
